package com.example.jdbi.config;

import org.jdbi.v3.core.Jdbi;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.AbstractFactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.NonNull;

public class JdbiMapperFactoryBean<T> extends AbstractFactoryBean<T> implements ApplicationContextAware {

    private final Class<T> clazz;
    private Jdbi jdbi;

    public JdbiMapperFactoryBean(Class<T> clazz) {
        this.clazz = clazz;
    }

    @Override
    public Class<?> getObjectType() {
        return clazz;
    }

    @Override
    protected @NonNull T createInstance() throws Exception {
        return jdbi.onDemand(this.clazz);
    }

    @Override
    public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
        this.jdbi = applicationContext.getBean(Jdbi.class);
    }
}
